package co.fitstart.coach.web.controller.courseware;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.resolver.Preloading;

import co.fitstart.coach.entity.courseware.CoursewareList;
import co.fitstart.coach.entity.security.Login;
import co.fitstart.coach.service.CourseService;
import co.fitstart.coach.service.CoursewareService;
import co.fitstart.coach.service.PrincipalService;
import co.fitstart.coach.service.WeeklyPlanService;
import co.fitstart.coach.web.resolver.Secure;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.course.schedule.CourseSchedule;
import co.fitstart.entity.courseware.exercise.ExerciseContent;
import co.fitstart.entity.courseware.exercise.PlannedSchedule;
import co.fitstart.entity.courseware.fitnessgroup.Courseware;
import co.fitstart.entity.courseware.fitnessgroup.FitnessGroup;
import co.fitstart.entity.courseware.movement.Movement;
import co.fitstart.entity.principal.Principal;

/**
 * 课件-课程
 * @author haiyan_xiao
 *
 */
@Controller
@RequestMapping("/rounds/{courseRoundId}/course-coursewares")
public class CourseCourseWareController {
    private static final Logger logger = LoggerFactory.getLogger(CourseCourseWareController.class);
    
    @Autowired
    private PrincipalService principalService;
    
    @Autowired
    private CourseService courseService;
    
    @Autowired
    private CoursewareService coursewareService;
    
    @Autowired
    private GenericDaoSupport genericDaoSupport;
    
    @Autowired
    private WeeklyPlanService weeklyPlanService;
    
    @RequestMapping(value = "", method = RequestMethod.GET)
    public ModelAndView list(@PathVariable("courseRoundId") Long courseRoundId) {
        ModelAndView modelAndView = new ModelAndView("courseware/batch/round-courseware-list");
        
        CourseRound courseRound = courseService.loadCourseRound(courseRoundId);
        
        if(courseRound != null) {
            List<CourseSchedule> courseSchedules = coursewareService.listCourseSchedule(courseRound);

            modelAndView.addObject("courseSchedules", courseSchedules);
            modelAndView.addObject("courseRound", courseRound);
        }
        
        return modelAndView;
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param session
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("courseRoundId") Long courseRoundId,
                             @PathVariable("courseScheduleId") Long courseScheduleId) {
        ModelAndView modelAndView = new ModelAndView("courseware/batch/course-schedule-detail");
        
        CourseSchedule courseSchedule = courseService.loadCourseSchedule(courseScheduleId);
        
        if(courseSchedule != null) {
            List<Courseware> coursewares = coursewareService.listCourseWares(courseSchedule);
            
            modelAndView.addObject("coursewares", coursewares);
            modelAndView.addObject("courseSchedule", courseSchedule);
        }
        
        return modelAndView;
    }
    
    /**
     * add courseware
     * @param login
     * @param courseRoundId
     * @param courseCoursewareId
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/coursewares/add", method = RequestMethod.GET)
    public ModelAndView addCourseware(@Secure Login login,
                                      @PathVariable("courseRoundId") Long courseRoundId,
                                      @PathVariable("courseScheduleId") Long courseScheduleId){
        ModelAndView modelAndView = new ModelAndView("courseware/batch/course-courseware-modify");
        
        Principal coach = principalService.load(Principal.class, login.getId());
        CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
        
        if(courseSchedule != null && !courseSchedule.isDisabled() && courseSchedule.getCoach() == coach) {
            PlannedSchedule plannedSchedule = weeklyPlanService.getPlannedSchedule(courseSchedule);
            
            if(plannedSchedule != null && !plannedSchedule.getContentList().isEmpty()) {
                List<ExerciseContent> contents = plannedSchedule.getContentList();
                
                if(!contents.isEmpty()) {
                    List<Movement> movements = coursewareService.listMovement(contents);
                    
                    modelAndView.addObject("movements", movements);
                }
                
            }
            
            modelAndView.addObject("courseSchedule", courseSchedule);
        }
        
        return modelAndView;
    }
    
    /**
     * edit courseware
     * @param login
     * @param courseRoundId
     * @param courseCoursewareId
     * @param coursewareId
     * @return
     */
//    @RequestMapping(value = "/{courseScheduleId}/coursewares/{coursewareId}/edit", method = RequestMethod.GET)
//    public ModelAndView editCourseware(@Secure Login login,
//                                       @PathVariable("courseRoundId") Long courseRoundId,
//                                       @PathVariable("courseScheduleId") Long courseScheduleId,
//                                       @PathVariable("coursewareId") Long coursewareId){
//        ModelAndView modelAndView = new ModelAndView("courseware/batch/course-courseware-modify");
//        
//        Principal coach = principalService.load(Principal.class, login.getId());
//        CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
//        
//        if(courseSchedule != null && !courseSchedule.isDisabled() && courseSchedule.getCoach() == coach) {
//            Courseware courseware = genericDaoSupport.load(Courseware.class, coursewareId);
//            
//            modelAndView.addObject("courseware", courseware);
//            modelAndView.addObject("courseSchedule", courseSchedule);
//        }
//        
//        return modelAndView;
//    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param courseScheduleId
     * @param courseware
     * @return
     */
//    @RequestMapping(value = "/{courseScheduleId}/coursewares", method = RequestMethod.POST)
//    public @ResponseBody String onCreate(@Secure Login login,
//                                         @PathVariable("courseRoundId") Long courseRoundId,
//                                         @PathVariable("courseScheduleId") Long courseScheduleId,
//                                         Courseware courseware){
//        Result result = new Result();
//        
//        try{
//            Principal coach = principalService.load(Principal.class, login.getId());
//            CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
//            
//            if(courseSchedule != null && courseSchedule.getCoach() == coach) {
//                coursewareService.createCourseware(courseSchedule, courseware);
//                
//                result.success().message("添加动作成功");
//            } else {
//                result.fail().message("添加动作失败");
//            }
//        } catch(Exception e){
//            logger.error("CourseCourseWareController#onCreate() error:", e);
//            
//            result.fail().message("添加动作失败");
//        }
//        
//        return JsonUtils.toJsonString(result);
//    }
    
    @RequestMapping(value = "/{courseScheduleId}/coursewares", method = RequestMethod.POST)
    public @ResponseBody String onCreate(@Secure Login login,
                                         @PathVariable("courseRoundId") Long courseRoundId,
                                         @PathVariable("courseScheduleId") Long courseScheduleId,
                                         @RequestParam("movementId") Long[] movementIds){
        Result result = new Result();
        
        try{
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
            
            if(courseSchedule != null && courseSchedule.getCoach() == coach && movementIds != null  && movementIds.length > 0) {
                coursewareService.createCourseware(courseSchedule, movementIds);
                
                result.success().message("添加动作成功");
            } else {
                result.fail().message("添加动作失败");
            }
        } catch(Exception e){
            logger.error("CourseCourseWareController#onCreate() error:", e);
            
            result.fail().message("添加动作失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param courseScheduleId
     * @param name
     * @param courseware
     * @return
     */
//    @RequestMapping(value = "/{courseScheduleId}/coursewares/create-and-add", method = RequestMethod.POST)
//    public @ResponseBody String onCreateAndAdd(@Secure Login login,
//                                               @PathVariable("courseRoundId") Long courseRoundId,
//                                               @PathVariable("courseScheduleId") Long courseScheduleId,
//                                               @RequestParam("name") String name,
//                                               Courseware courseware){
//        Result result = new Result();
//        
//        try{
//            Principal coach = principalService.load(Principal.class, login.getId());
//            CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
//            
//            if(courseSchedule != null && courseSchedule.getCoach() == coach && StringUtils.isNotBlank(name)) {
//                coursewareService.createCourseware(courseSchedule, courseware, name.trim());
//                
//                result.success().message("添加动作成功");
//            } else {
//                result.fail().message("添加动作失败");
//            }
//        } catch(Exception e){
//            logger.error("CourseCourseWareController#onCreateAndAdd() error:", e);
//            
//            result.fail().message("添加动作失败");
//        }
//        
//        return JsonUtils.toJsonString(result);
//    }
    
    @RequestMapping(value = "/{courseScheduleId}/coursewares/create-and-add", method = RequestMethod.POST)
    public @ResponseBody String onCreateAndAdd(@Secure Login login,
                                               @PathVariable("courseRoundId") Long courseRoundId,
                                               @PathVariable("courseScheduleId") Long courseScheduleId,
                                               @RequestParam("name") String name){
        Result result = new Result();
        
        try{
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
            
            if(courseSchedule != null && courseSchedule.getCoach() == coach && StringUtils.isNotBlank(name)) {
                coursewareService.createCourseware(courseSchedule, name.trim());
                
                result.success().message("添加动作成功");
            } else {
                result.fail().message("添加动作失败");
            }
        } catch(Exception e){
            logger.error("CourseCourseWareController#onCreateAndAdd() error:", e);
            
            result.fail().message("添加动作失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param courseScheduleId
     * @param groupId
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/coursewares/action-group", method = RequestMethod.POST)
    public @ResponseBody String onCreateGroup(@Secure Login login,
                                              @PathVariable("courseRoundId") Long courseRoundId,
                                              @PathVariable("courseScheduleId") Long courseScheduleId,
                                              @RequestParam("groupId") Long groupId){
        Result result = new Result();
        
        try{
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
            
            if(courseSchedule != null && courseSchedule.getCoach() == coach) {
                FitnessGroup fitnessGroup = coursewareService.loadFitnessGroup(groupId);
                
                coursewareService.createCoursewareGroup(courseSchedule, fitnessGroup);
                
                result.success().message("添加动作组成功");
            } else {
                result.fail().message("添加动作组失败");
            }
        } catch(Exception e){
            logger.error("CourseCourseWareController#onCreateGroup() error:", e);
            
            result.fail().message("添加动作组失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * on edit courseware
     * @param login
     * @param courseRoundId
     * @param courseCoursewareId
     * @param courseware
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/coursewares/{coursewareId}", method = RequestMethod.PATCH)
    public @ResponseBody String onEditCourseware(@Secure Login login,
                                                 @PathVariable("courseRoundId") Long courseRoundId,
                                                 @PathVariable("courseScheduleId") Long courseScheduleId,
                                                 @Preloading("coursewareId") Courseware courseware){
        Result result = new Result();
        
        try{
            Principal coach = principalService.load(Principal.class, login.getId());
            
            if(!courseware.isDisabled() && courseware.getCourseSchedule().getCoach() == coach) {
                coursewareService.editCourseware(courseware);
                
                result.success().message("修改动作成功");
            } else {
                result.fail().message("修改动作失败");
            }
        } catch(Exception e){
            logger.error("CourseCourseWareController#onEditCourseware() error:", e);
            
            result.fail().message("修改动作失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param courseScheduleId
     * @param courseware
     * @return
     */
//    @RequestMapping(value = "/{courseScheduleId}/coursewares/{coursewareId}/edit-and-add", method = RequestMethod.PATCH)
//    public @ResponseBody String onEditAndAdd(@Secure Login login,
//                                             @PathVariable("courseRoundId") Long courseRoundId,
//                                             @PathVariable("courseScheduleId") Long courseScheduleId,
//                                             @RequestParam("name") String name,
//                                             @Preloading("coursewareId") Courseware courseware){
//        Result result = new Result();
//        
//        try{
//            Principal coach = principalService.load(Principal.class, login.getId());
//            
//            if(!courseware.isDisabled() && courseware.getCourseSchedule().getCoach() == coach && StringUtils.isNotBlank(name)) {
//                coursewareService.editCourseware(courseware, name.trim());
//                
//                result.success().message("修改动作成功");
//            } else {
//                result.fail().message("修改动作失败");
//            }
//        } catch(Exception e){
//            logger.error("CourseCourseWareController#onEditAndAdd() error:", e);
//            
//            result.fail().message("修改动作失败");
//        }
//        
//        return JsonUtils.toJsonString(result);
//    }
    
    /**
     * on delete courseware
     * @param login
     * @param courseRoundId
     * @param courseCoursewareId
     * @param coursewareIds
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/coursewares", method = RequestMethod.DELETE)
    public @ResponseBody String onDeleteCourseware(@Secure Login login,
                                                   @PathVariable("courseRoundId") Long courseRoundId,
                                                   @PathVariable("courseScheduleId") Long courseScheduleId,
                                                   @RequestParam("coursewareId") Long[] coursewareIds){
        Result result = new Result();
        
        try{
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
            
            if(courseSchedule != null && courseSchedule.getCoach() == coach) {
                coursewareService.deleteCourseware(courseSchedule, coursewareIds);
                
                result.success().message("删除动作成功");
            } else {
                result.fail().message("删除动作失败");
            }
        } catch(BusinessException e) {
            result.fail().message(e.getMessage());
        } catch(Exception e){
            logger.error("CourseCourseWareController#onDeleteCourseware() error:", e);
            
            result.fail().message("删除动作失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * 
     * @param login
     * @param courseRoundId
     * @param courseCoursewareId
     * @param coursewareId
     * @return
     */
    @RequestMapping(value = "/{courseScheduleId}/coursewares/{coursewareId}", method = RequestMethod.GET)
    public ModelAndView coureware(@PathVariable("courseRoundId") Long courseRoundId,
                                  @PathVariable("courseScheduleId") Long courseScheduleId,
                                  @PathVariable("coursewareId") Long coursewareId) {
        ModelAndView modelAndView = new ModelAndView("courseware/batch/course-courseware-detail");
        
        Courseware courseware = genericDaoSupport.load(Courseware.class, coursewareId);
        
        if(courseware != null) {
            modelAndView.addObject("courseware", courseware);
            modelAndView.addObject("session", coursewareService.getRank(courseware.getCourseSchedule()));
        }
        
        return modelAndView;
    }
    
    @RequestMapping(value = "/{courseScheduleId}/coursewares", method = RequestMethod.PATCH)
    public @ResponseBody String onEditCoursewares(@Secure Login login,
                                                  @PathVariable("courseRoundId") Long courseRoundId,
                                                  @PathVariable("courseScheduleId") Long courseScheduleId,
                                                  CoursewareList coursewareList){
        Result result = new Result();
        
        try{
            Principal coach = principalService.load(Principal.class, login.getId());
            CourseSchedule courseSchedule = genericDaoSupport.load(CourseSchedule.class, courseScheduleId);
            
            if(courseSchedule != null && courseSchedule.getCoach() == coach
                    && coursewareList.getCoursewares() != null
                    && !coursewareList.getCoursewares().isEmpty()) {
                coursewareService.editCourseware(courseSchedule, coursewareList.getCoursewares());
                
                result.success().message("修改动作成功");
            } else {
                result.fail().message("修改动作失败");
            }
        } catch(BusinessException e) {
            result.fail().message(e.getMessage());
        } catch(Exception e){
            logger.error("CourseCourseWareController#onEditCoursewares() error:", e);
            
            result.fail().message("修改动作失败");
        }
        
        return JsonUtils.toJsonString(result);
    }
}
